import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Spin} from 'antd';
import {hasPermissions} from './utils';
import {PERMISSION} from './constants';
import {PAGE} from '../constants';
import routes from './routes';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
import CommonDetail from './CommonDetail';
import Export from './Export';
export class Detail extends React.PureComponent {
    state = {
        loading: false,
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleAbandonClick = () => {
        this.setState({
            loading: true
        });
        this.props.onClickAbandon().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };

    onClickExport = () => {
        const {id, isInvoiceCompany} = this.props.detail;
        const href = isInvoiceCompany
            ? `#dcs/afterSales/reportpdf.html?name=ClaimProformaInvoiceEn&id=${id}&title=${encodeURI(
                '索赔结算形式发票'
            )}`
            : `#dcs/afterSales/reportpdf.html?name=ClaimProformaInvoiceCn&id=${id}&title=${encodeURI(
                '索赔结算形式发票'
            )}`;
        window.open(href);
    }

    render() {
        const {options = []} = this.props.detail;
        const operations = [];
        if(hasPermissions(this.props.permissions, PERMISSION.confirm) && hasPermissions(options, PERMISSION.confirm))
            operations.push(
                <Button key="confirm" href={`#${routes.confirm.format(this.props.id)}`} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.confirm',
                        defaultMessage: '开票确认'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(options, PERMISSION.approve))
            operations.push(
                <Button key="approve" href={`#${routes.approve.format(this.props.id)}`} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.approve',
                        defaultMessage: '审核'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.export) && hasPermissions(options, PERMISSION.export))
            operations.push(
                <Button key="export" onClick={this.onClickExport} size="small">
                    {this.props.intl.formatMessage({
                        id: 'detail.btn.export',
                        defaultMessage: '导出'
                    })}
                </Button>
            );
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(options, PERMISSION.abandon))
            operations.push(
                <WrappedPopconfirm
                    id="abandon"
                    key="abandon"
                    title={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.message',
                        defaultMessage: '是否继续?'
                    })}
                    okText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.confirm',
                        defaultMessage: '确认'
                    })}
                    cancelText={this.props.intl.formatMessage({
                        id: 'detail.popconfirm.cancel',
                        defaultMessage: '取消'
                    })}
                    onConfirm={this.handleAbandonClick}>
                    <Button size="small">
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.abandon',
                            defaultMessage: '作废'
                        })}
                    </Button>
                </WrappedPopconfirm>
            );
        
        return (
            <div className={styles.detail}>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <CommonDetail detail={this.props.detail} showBrand={this.props.showBrand} operations={operations} isDealerUser={this.props.isDealerUser} isDetail={true} />
                </Spin>
                <div className="page-toolbar">
                    <Button type="primary" disabled={this.props.loading} onClick={this.props.onCancel}>
                        {this.props.intl.formatMessage({
                            id: 'detail.btn.retrun',
                            defaultMessage: '返回'
                        })}
                    </Button>
                </div>
            </div>
        );
    }
}
Detail.propTypes = {
    detail: PropTypes.object.isRequired,
    id: PropTypes.string.isRequired,
    init: PropTypes.func.isRequired,
    isDealerUser: PropTypes.bool.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickAbandon: PropTypes.func.isRequired,
    onClickExport: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object,
    showBrand: PropTypes.bool
};
import {connect} from 'react-redux';
import {getDetail, clearData, onClickAbandonForDetail, tableSearch, exportDetailData} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const getDetailData = selectorFactory(['page', 'domainData', 'detail', 'data']);

const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']) || state.getIn(['page', 'domainData', 'initData', 'isFetching']),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    detail: getDetailData(state),
    showBrand: state.getIn(['page', 'domainData', 'brands', 'data']).size > 1,
    permissions: getPermissions(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getDetail(ownProps.id)),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onClickExport: id => dispatch(exportDetailData(id)),
    onClickAbandon: () =>
        dispatch(onClickAbandonForDetail(ownProps.id)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }

            return res.ok;
        }),
    onUmount: () => dispatch(clearData()),
});

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Detail));
